﻿using Klear.Library.Models;
using Newtonsoft.Json.Linq;

namespace Klear.Library.Helpers;

public class JsonHelper
{
    public static IncomeAndExpensesModel JsonToIncomeAndExpenses(string json)
    {
        Console.WriteLine("开始JSON转换...");
        JObject responseMsg = JObject.Parse(json);
        string innerJsonText = responseMsg["output"]?["text"]?.ToString();
        
        if (string.IsNullOrEmpty(innerJsonText))
        {
            throw new Exception("Inner JSON text is null or empty.");
        }

        // 解析嵌套的 JSON 数据
        JObject innerJson = JObject.Parse(innerJsonText);
        string title = innerJson["title"]?.ToString() ?? "支出"; // 默认值为 "支出"
        decimal amount = innerJson["amount"]?.ToObject<decimal?>() ?? 0m; // 默认金额为 0
        string category = innerJson["category"]?.ToString() ?? "其他"; // 默认值为 "支出"
        string notes = innerJson["notes"]?.ToString() ?? string.Empty; // 默认值为空字符串
        Console.WriteLine("JSON解析完成,正在数据规范化...");
        IncomeAndExpensesModel model = new IncomeAndExpensesModel();
                
        model.Title = title;
        model.Amount = amount;
        model.Category = category;
        model.Notes = notes;
        model.CreateTime = DateTime.Now;
        model.UpdateTime = DateTime.Now;
        Console.WriteLine("处理完成!");
        return model;
    }

    public static AlmanacModel JsonToAlmanac(string json)
    {
        AlmanacModel model = new AlmanacModel();
        JObject jsonResponse = JObject.Parse(json);

        if (jsonResponse["code"]?.ToString() == "200")
        {
            JObject result = (JObject)jsonResponse["result"];
            model.Gregoriandate=result["gregoriandate"]?.ToString() ?? "";
            model.Lunardate=result["lunardate"]?.ToString() ?? "";
            model.Fitness = result["fitness"]?.ToString() ?? "";
            model.Taboo = result["taboo"]?.ToString() ?? "";
            model.Chongsha = result["chongsha"]?.ToString() ?? "";
            model.Tiangandizhiyear = result["tiangandizhiyear"]?.ToString() ?? "";
            model.Tiangandizhimonth = result["tiangandizhimonth"]?.ToString() ?? "";
            model.Tiangandizhiday = result["tiangandizhiday"]?.ToString() ?? "";
            model.Jieqi = result["jieqi"]?.ToString() ?? "";
                    
        }
        else
        {
            Console.WriteLine("API Error: " + jsonResponse["msg"]?.ToString());
            return null;
        }
        return model;
    }

    public static string JsonToString(string json)
    {
        Console.WriteLine("开始OCR JSON处理...");
        JObject jsonData = JObject.Parse(json);
        string content = jsonData["content"]?.ToString() ?? string.Empty;
        Console.WriteLine("OCR处理完成,开始进行文本处理!");
        return content;
    }
}